package com.app114.app.android.rk;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TabHost;
import android.widget.Toast;

import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnCreateOptionsMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnOptionsItemSelectedListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.app114.app.android.rk.conf.Conf;
import com.app114.app.android.rk.utils.DeviceUtil;
import com.app114.app.android.rk.utils.Exit;
import com.app114.app.android.rk.utils.UmengUtil;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.waps.AppConnect;

/**
 * This demonstrates how you can implement switching between the tabs of a TabHost through fragments. It uses a trick (see the code below) to allow
 * the tabs to switch between fragments instead of simple views.
 */
public class Main extends FragmentActivity implements OnCreateOptionsMenuListener, OnNavigationListener, OnOptionsItemSelectedListener,
		UmengUpdateListener {
	public static final String ITEM[] = { "首页", "收藏", "历史" };
	TabHost mTabHost;
	TabManager mTabManager;
	ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
	ActionBar mActionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar = mSherlock.getActionBar();
		mActionBar.setDisplayShowTitleEnabled(false);
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		Context context = mActionBar.getThemedContext();
		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.home_item, R.layout.sherlock_spinner_item);
		list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		mActionBar.setListNavigationCallbacks(list, this);

		mSherlock.setContentView(R.layout.activity_main);
		// setContentView(R.layout.activity_main);
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();

		mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);

		mTabManager.addTab(mTabHost.newTabSpec("首页").setIndicator("首页"), HomeFragment.class, null);
		mTabManager.addTab(mTabHost.newTabSpec("收藏").setIndicator("收藏"), Favoriten.class, null);
		mTabManager.addTab(mTabHost.newTabSpec("历史").setIndicator("历史"), BrowsingHistory.class, null);

		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		}
		UmengUtil.onError(this);
		UmengUtil.updateCos(this);

		AppConnect.getInstance(Conf.WAPS_ID, Conf.WAPS_PID, this);
	}

	@Override
	protected void onResume() {
		UmengUtil.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		UmengUtil.onPause(this);
		super.onPause();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("tab", mTabHost.getCurrentTabTag());
	}

	@Override
	protected void onDestroy() {
		AppConnect.getInstance(this).finalize();
//		DianJinPlatform.destroy() ;
		super.onDestroy();
	}

	/**
	 * This is a helper class that implements a generic mechanism for associating fragments with the tabs in a tab host. It relies on a trick.
	 * Normally a tab host has a simple API for supplying a View or Intent that each tab will show. This is not sufficient for switching between
	 * fragments. So instead we make the content part of the tab host 0dp high (it is not shown) and the TabManager supplies its own dummy view to
	 * show as the tab content. It listens to changes in tabs, and takes care of switch to the correct fragment shown in a separate content area
	 * whenever the selected tab changes.
	 */
	public static class TabManager implements TabHost.OnTabChangeListener {
		private final FragmentActivity mActivity;
		private final TabHost mTabHost;
		private final int mContainerId;
		private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
		TabInfo mLastTab;

		static final class TabInfo {
			private final String tag;
			private final Class<?> clss;
			private final Bundle args;
			private Fragment fragment;

			TabInfo(String _tag, Class<?> _class, Bundle _args) {
				tag = _tag;
				clss = _class;
				args = _args;
			}
		}

		static class DummyTabFactory implements TabHost.TabContentFactory {
			private final Context mContext;

			public DummyTabFactory(Context context) {
				mContext = context;
			}

			@Override
			public View createTabContent(String tag) {
				View v = new View(mContext);
				v.setMinimumWidth(0);
				v.setMinimumHeight(0);
				return v;
			}
		}

		public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
			mActivity = activity;
			mTabHost = tabHost;
			mContainerId = containerId;
			mTabHost.setOnTabChangedListener(this);
		}

		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
			tabSpec.setContent(new DummyTabFactory(mActivity));
			String tag = tabSpec.getTag();

			TabInfo info = new TabInfo(tag, clss, args);

			// Check to see if we already have a fragment for this tab, probably
			// from a previously saved state. If so, deactivate it, because our
			// initial state is that a tab isn't shown.
			info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
			if (info.fragment != null && !info.fragment.isDetached()) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
				ft.detach(info.fragment);
				ft.commit();
			}

			mTabs.put(tag, info);
			mTabHost.addTab(tabSpec);
		}

		@Override
		public void onTabChanged(String tabId) {
			TabInfo newTab = mTabs.get(tabId);
			if (mLastTab != newTab) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
				if (mLastTab != null) {
					if (mLastTab.fragment != null) {
						ft.detach(mLastTab.fragment);
					}
				}
				if (newTab != null) {
					if (newTab.fragment == null) {
						newTab.fragment = Fragment.instantiate(mActivity, newTab.clss.getName(), newTab.args);
						ft.add(mContainerId, newTab.fragment, newTab.tag);
					} else {
						ft.attach(newTab.fragment);
					}
				}

				mLastTab = newTab;
				ft.commit();
				mActivity.getSupportFragmentManager().executePendingTransactions();
			}
		}
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		mTabManager.onTabChanged(ITEM[itemPosition]);
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		return mSherlock.dispatchCreateOptionsMenu(menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		mSherlock.getMenuInflater().inflate(R.menu.activity_general, menu);
		return true;
	}

	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		return mSherlock.dispatchOptionsItemSelected(item);
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			DeviceUtil.startctivity(this, new Intent(this, Setting.class));
			break;
		case R.id.menu_search:
			onSearchRequested();
			break;

		default:
			break;
		}
		return true;
	}

	Exit exit = new Exit();

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			pressAgainExit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 13 再按一次退出程序。 14
	 */
	private void pressAgainExit() {
		if (exit.isExit()) {
			finish();
		} else {
			Toast.makeText(getApplicationContext(), "再按一次退出程序", 1).show();
			exit.doExitInOneSecond();
		}
	}

	@Override
	public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
		switch (updateStatus) {
		case 0: // has update
			DeviceUtil.toast(this, "发现新版本，请到设置界面升级！") ;
			break;
		}

	}

}
